import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

import { ElMessage } from 'element-plus'

interface ResponseData<T = any> {
  code: number;
  message: string;
  data: T;
}

const baseURL:string = 'http://127.0.0.1:3000'

class HttpClient {
  private readonly instance: AxiosInstance;

  constructor() {
    // process.env.VUE_APP_BASE_API
    this.instance = axios.create({
      baseURL
    });

    // this.instance.interceptors.request.use(
    //   (config: AxiosRequestConfig) => {
    //     // 在请求发送之前做些什么
    //     return config;
    //   },
    //   (error: any) => {
    //     // 对请求错误做些什么
    //     return Promise.reject(error);
    //   }
    // );

    this.instance.interceptors.response.use(
      (response: AxiosResponse<any>) => {
        // 对响应数据做些什么
        const res = response.data;
        // console.log(res);
        
        // if (res.code !== 200) {
        //   console.error(res.message);
        // }
        return res;
      },
      (error: any) => {
        // 对响应错误做些什么
        console.error(error);
        return Promise.reject(error);
      }
    );
  }

  public request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<ResponseData<T>>(config)
        .then((res:any) => {
          resolve(res);
        })
        .catch((err:any) => {
          ElMessage({
            message: '服务异常',
            grouping: true,
            type: 'error',
          })
          reject(err);
        });
    });
  }

  public get<T = any>(url: string, params?: any): Promise<T> {
    return this.request<T>({
      method: 'get',
      url,
      params
    });
  }

  public post<T = any>(url: string, data?: any): Promise<T> {
    return this.request<T>({
      method: 'post',
      url,
      data
    });
  }

  public postFile<T = any>(url: string, data?: any): Promise<T> {
    return this.request<T>({
      method: 'post',
      url,
      data,
      headers:{
        'Content-Type': 'multipart/form-data'
      }
    });
  }

  public put<T = any>(url: string, data?: any): Promise<T> {
    return this.request<T>({
      method: 'put',
      url,
      data
    });
  }

  public delete<T = any>(url: string, params?: any): Promise<T> {
    return this.request<T>({
      method: 'delete',
      url,
      params
    });
  }
}

export default new HttpClient();